<template>
    <ClientOnly>
        <popup
            :show="visible"
            :loading="loading"
            :async-close="true"
            width="440px"
            title="创建智能体"
            @confirm="handleSubmit"
            @close="emits('close')"
        >
            <div class="p-6 pb-0">
                <el-form
                    ref="formRef"
                    class="layout-forms"
                    :model="formData"
                    :rules="formRules"
                    label-width="90px"
                >
                    <el-form-item label="智能体名称" prop="name">
                        <el-input v-model="formData.name" placeholder="请输入智能体名称" maxlength="32" />
                    </el-form-item>
                    <el-form-item label="智能体简介" prop="intro">
                        <el-input
                            v-model="formData.intro"
                            placeholder="用一句话介绍智能体"
                            type="textarea"
                            show-word-limit
                            :rows="5"
                        />
                    </el-form-item>
                </el-form>
            </div>
        </popup>
    </ClientOnly>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import robotSmarterApi from '~/api/agent/robot/smarter'

const emits = defineEmits(['confirm', 'close'])

// 基础参数
const loading = ref<boolean>(false)
const visible = ref<boolean>(false)
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
    logo: '',  // 智能体图标
    name: '',  // 智能体名称
    intro: ''  // 智能体简介
})

// 表单规则
const formRules: any = reactive({
    name: [
        { required: true, message: '智能体名称不能为空', trigger: 'blur' },
        { max: 32, message: '智能体名称不能大于32个字符', trigger: 'blur' }
    ],
    intro: [
        { max: 800, message: '智能体名称简介不能大于800个字符', trigger: 'blur' }
    ]
})

/**
 * 提交表单
 */
const handleSubmit = async () => {
    loading.value = true
    await formRef.value?.validate()
    await robotSmarterApi.add(formData)
        .then(() => {
            emits('close')
            emits('confirm')
            visible.value = false
            feedback.msgSuccess('创建成功')
        })
        .finally(() => {
            loading.value = false
        })
}

/**
 * 打开窗口
 */
const open = () => {
    visible.value = true
}

defineExpose({
    open
})
</script>